package utils;


import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class MyHttpURLConection_operator extends BaseHttp {

    private String serverUrl;
    private Map<String, String> map_token;

    private static class SingleInstance {
        private static final MyHttpURLConection_operator conection_operator = new MyHttpURLConection_operator();
    }

    private MyHttpURLConection_operator() {

    }

    public static MyHttpURLConection_operator newInstance() {
        return SingleInstance.conection_operator;
    }

    public MyHttpURLConection_operator setCofig(String serverUrl, Map<String, String> map) {
        this.serverUrl = serverUrl;
        this.map_token = map;
        return SingleInstance.conection_operator;
    }

    public BaseHttp doGet(String path) throws Exception {

        return HTTPConnection(serverUrl + path, map_token, "GET");
    }

    public BaseHttp doPost$(String path, String datas) throws Exception {

        return HTTPConnection(serverUrl + path, datas, map_token, "POST");
    }

    public BaseHttp doPost$(String path, Map<String, Object> params) throws Exception {
        return HTTPConnection(serverUrl + path, params, map_token, "POST");
    }

    public BaseHttp doGet$(String path, Map<String, Object> params) throws Exception {

        return HTTPConnection(serverUrl + path, params, map_token, "GET");

    }


    public String doPost(String path, String datas) throws Exception {

        return HTTPConnection(serverUrl + path, datas, map_token, "POST").getResponse();
    }

    public String doPost(String path, Map<String, Object> params) throws Exception {
        return HTTPConnection(serverUrl + path, params, map_token, "POST").getResponse();
    }

    public String doGet(String path, Map<String, Object> params) throws Exception {

        return HTTPConnection(serverUrl + path, params, map_token, "GET").getResponse();

    }

    public Map<String, List<String>> doGetHeaders(String path) throws Exception {

        HttpURLConnection connection;

        URL url = new URL((serverUrl + path));
        Map<String, List<String>> map = new HashMap<>();
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        connection.getHeaderFields().forEach((k, v) -> {
            if (Optional.ofNullable(k).isPresent())
                map.put(k.toLowerCase(), v);
        });
        return map;

    }

}

